// import * as Cesium from 'cesium'
import CesiumNavigation from "cesium-navigation-es6";

export default class KyViewer extends Cesium.Viewer {
  /**
   * 构造方法
   * @param elementId 加载三维地图的div的id (required)
   * @param options 需要重新设置的cesium.Viewer的原生属性，可以不传
   */
  constructor(elementId, options) {
    // debugger
    const initOpt = {
      // 不显示时间线
      timeline: false,
      // 不显示时间快进快退组件
      animation: false,
      // 不显示全屏组件
      fullscreenButton: false,
      // 查找位置工具，查找到之后会将镜头对准找到的地址
      geocoder: false,
      // 视角返回初始位置。
      homeButton: false,
      // 选择视角的模式，有三种：3D、2D、哥伦布视图（CV）。
      sceneModePicker: false,
      // 图层选择器，选择要显示的地图服务和地形服务
      baseLayerPicker: false,
      navigationHelpButton: false,
      // 关闭沙盒
      infoBox: false,
      ...options,
    };
    super(elementId, initOpt);
    this.navigationOptions = {};
    // 事件注册
    this.handler = new Cesium.ScreenSpaceEventHandler(this.scene.canvas);
    // 判断是否支持图像渲染像素化处理,保证高分屏效果
    if (Cesium.FeatureDetection.supportsImageRenderingPixelated()) {
      this.resolutionScale = window.devicePixelRatio;
    }
    this.cesiumWidget.creditContainer.style.display = "none";
    this.scaleScreenVal = 1;
    // 限制视角不能进入地下
    this.scene.globe.depthTestAgainstTerrain = false;
    // 调整光照为平行光，固定角度，不随时间变化
    this.scene.light = new Cesium.DirectionalLight({
      direction: new Cesium.Cartesian3(2.3549, -0.8909, -0.2833),
      intensity: 1,
    });
    this.onRightClick((target) => {
      const feature = this.scene.pick(target.position);
      const heading = this.camera.heading;
      const pitch = this.camera.pitch;
      const roll = this.camera.roll;
      // 相机的经纬坐标
      const carto = this.camera.positionCartographic;
      const { height, longitude, latitude } = carto;
      const result = {
        height,
        longitude: Cesium.Math.toDegrees(longitude),
        latitude: Cesium.Math.toDegrees(latitude),
        heading,
        pitch,
        roll,
      };
      console.log("相机参数", JSON.stringify(result));

      if (feature === undefined) {
        const cartesian3 = this.scene.globe.pick(
          this.camera.getPickRay(target.position),
          this.scene,
        );
        const cartographic = Cesium.Cartographic.fromCartesian(cartesian3);
        console.log(
          "点击了地形经纬高",
          Cesium.Math.toDegrees(cartographic.longitude),
          Cesium.Math.toDegrees(cartographic.latitude),
          cartographic.height,
        );
      } else {
        const cartesian3 = this.scene.pickPosition(target.position);
        const cartographic = Cesium.Cartographic.fromCartesian(cartesian3);
        console.log(
          "点击了模型经纬高",
          Cesium.Math.toDegrees(cartographic.longitude),
          Cesium.Math.toDegrees(cartographic.latitude),
          cartographic.height,
        );
      }
    });
    // this.hideGlobe()
    this.showGlobe(); // 显示地球
  }

  /**
   * 显示地球、天空、太阳，月亮等
   */
  showGlobe() {
    this.scene.sun.show = false;
    this.scene.moon.show = false;
    // 关闭阴影
    this.shadows = false;
    // 关闭光源
    this.scene.globe.enableLighting = false;
    this.scene.postProcessStages.bloom.enabled = false;
    this.scene.skyAtmosphere.show = false;
    this.scene.skyBox.show = true;
    this.scene.undergroundMode = true;
    this.scene.globe.show = true;
    this.scene.globe.baseColor = new Cesium.Color(0, 0, 0, 0);
    this.scene.backgroundcolor = new Cesium.Color(0, 0, 0, 0);
  }

  /**
   * 关闭显示地球、天空、太阳，月亮等
   */
  hideGlobe() {
    this.scene.sun.show = false; // 在Cesium1.6(不确定)之后的版本会显示太阳和月亮，不关闭会影响展示
    this.scene.moon.show = false;
    this.scene.skyBox.show = false; // 关闭天空盒，否则会显示天空颜色

    this.scene.undergroundMode = true; // 重要，开启地下模式，设置基色透明，这样就看不见黑色地球了
    this.scene.globe.show = false; // 不显示地球，这条和地球透明度选一个就可以
    this.scene.globe.baseColor = new Cesium.Color(0, 0, 0, 0);
    this.scene.backgroundcolor = new Cesium.Color(0, 0, 0, 0);
  }

  /**
   * 设置导航条,参数为相机
   */
  setNavigation(camera) {
    const mycartographic = camera.positionCartographic;
    const myheading = camera.heading;
    const mypitch = camera.pitch;
    const myroll = camera.roll;
    this.navigationOptions.defaultResetView = mycartographic;
    this.navigationOptions.orientation = {
      heading: myheading,
      pitch: mypitch,
      roll: myroll,
    };
    this.navigationOptions.zoomInSvg =
      '<svg t="1656395878336" class="icon" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="14165" width="16" height="16"><path d="M902.343 570.936h-331.78v331.833c0 32.337-26.226 58.537-58.564 58.537-32.337 0-58.563-26.2-58.563-58.537V570.936H121.654c-32.364 0-58.564-26.2-58.564-58.538 0-32.325 26.203-58.537 58.564-58.537h331.78V122.028c0-32.325 26.226-58.537 58.563-58.537 32.338 0 58.564 26.213 58.564 58.537v331.834h331.78c32.364 0 58.565 26.211 58.565 58.535-0.001 32.337-26.2 58.536-58.565 58.536z" p-id="14166"></path></svg>';
    this.navigationOptions.zoomOutSvg =
      '<svg t="1656395899714" class="icon" viewBox="0 0 1025 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="15013" width="16" height="16"><path d="M973.154 563.218 51.222 563.218c-28.275 0-51.222-22.946-51.222-51.214 0-28.276 22.946-51.222 51.222-51.222L973.154 460.782c28.33 0 51.222 22.946 51.222 51.222C1024.375 540.272 1001.484 563.218 973.154 563.218L973.154 563.218z" p-id="15014"></path></svg>';
    this.navigationOptions.resetSvg =
      '<svg t="1656395704657" class="icon" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="10009" width="18" height="18"><path d="M887.8 394.8H719.3c-21.5 0-38.9-17.4-38.9-38.9s17.4-38.9 38.9-38.9H787c-61-86.2-161.3-142.5-275-142.5-186.1 0-336.9 150.8-336.9 336.9 0 186.1 150.8 336.9 336.9 336.9 186 0 336.9-150.8 336.9-336.9 0-21.5 17.4-38.9 38.9-38.9s38.9 17.4 38.9 38.9C926.7 740.4 741 926 512 926S97.4 740.4 97.4 511.4C97.4 282.4 283 96.8 512 96.8c139 0 261.7 68.5 336.9 173.5v-69.8c0-21.5 17.4-38.9 38.9-38.9s38.9 17.4 38.9 38.9V356c0 21.4-17.5 38.8-38.9 38.8z m0 0" p-id="10010"></path></svg>';
    this.navigation = new CesiumNavigation(this, this.navigationOptions);
  }

  /**
   * 设置相机位置
   * @param position
   * @param position.longitude 经度
   * @param position.latitude 纬度
   * @param position.height 高度（米）
   * @param position.heading 旋转
   * @param position.pitch 旋转
   * @param position.roll 旋转
   */
  setCameraView(position) {
    const car3 = Cesium.Cartesian3.fromDegrees(
      position.longitude,
      position.latitude,
      position.height,
    );
    this.camera.setView({
      destination: car3,
      orientation: {
        heading: position.heading,
        pitch: position.pitch,
        roll: position.roll,
      },
    });
  }

  /**
   * 设置摄像机飞到指定球
   * @param sphere
   */
  setCameraFlyToBoundingSphere(sphere, options) {
    this.camera.flyToBoundingSphere(sphere, { ...options });
  }

  /**
   * 设置相机飞行至指定位置
   * @param positio
   * @param position.longitude 经度
   * @param position.latitude 纬度
   * @param position.height 高度（米）
   * @param position.heading 旋转
   * @param position.pitch 旋转
   * @param position.roll 旋转
   * @param position.duration 飞行时间
   * @param completeFun 完成飞行之后的回调函数
   */
  setCameraFlyTo(position, completeFun = null) {
    this.camera.flyTo({
      destination: Cesium.Cartesian3.fromDegrees(
        position.longitude,
        position.latitude,
        position.height,
      ),
      orientation: {
        heading: position.heading || 2.3910984163425497,
        pitch: position.pitch || -1.0472040795772881,
        roll: position.roll || 0,
      },
      duration: position.duration,
      // 完成飞行后的回调函数
      complete: completeFun,
    });
  }

  /**
   * 销毁kyviewer实例
   */
  destroy() {
    console.log("datasourece", this.dataSources);
    this.dataSources.removeAll(true);
    super.destroy();
  }

  /**
   * 左键点击事件（返回坐标）
   * @param callback 事件回调
   */
  onClick(callback) {
    // debugger
    this.handler.setInputAction(
      callback,
      Cesium.ScreenSpaceEventType.LEFT_CLICK,
    );
  }

  /**
   * 鼠标移动事件 (返回坐标)
   * @param callback
   */
  onMove(callback) {
    this.handler.setInputAction(
      callback,
      Cesium.ScreenSpaceEventType.MOUSE_MOVE,
    );
  }

  /**
   * 右键点击事件
   * @param callback 事件回调
   */
  onRightClick(callback) {
    this.handler.setInputAction(
      callback,
      Cesium.ScreenSpaceEventType.RIGHT_CLICK,
    );
  }

  /**
   * 左键双击事件
   * @param callback 事件回调
   */
  onLeftDoubleClick(callback) {
    this.handler.setInputAction(
      callback,
      Cesium.ScreenSpaceEventType.LEFT_DOUBLE_CLICK,
    );
  }

  /**
   * 鼠标中键滚轮的点击事件
   * @param callback
   */
  onMiddleClick(callback) {
    this.handler.setInputAction(
      callback,
      Cesium.ScreenSpaceEventType.MIDDLE_CLICK,
    );
  }

  /**
   * 点击Feature的事件（返回Feature的id)
   * @param callback  回调方法 (required)
   */
  onClickFeature(callback) {
    this.handler.setInputAction((movement) => {
      // console.log(this.scaleScreenVal)
      movement.position.x = movement.position.x / this.scaleScreenVal;
      movement.position.y = movement.position.y / this.scaleScreenVal;
      // debugger
      const pickedLabel = this.scene.pick(movement.position);
      if (Cesium.defined(pickedLabel)) {
        if (pickedLabel.id) {
          callback(pickedLabel.id.id, movement);
        }
      }
    }, Cesium.ScreenSpaceEventType.LEFT_CLICK);
  }

  /**
   * 销毁鼠标事件
   */
  destroyHandler() {
    this.handler.removeInputAction(Cesium.ScreenSpaceEventType.LEFT_CLICK);
    this.handler.removeInputAction(Cesium.ScreenSpaceEventType.MOUSE_MOVE);
    this.handler.removeInputAction(Cesium.ScreenSpaceEventType.RIGHT_CLICK);
  }
}
